<template>
   <div>
    <el-breadcrumb>
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
      <el-breadcrumb-item>销售管理</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content">
      <el-row>
        <el-col :span="12">
          <e-heading style="margin-top:0" :grade="'1'">销售管理</e-heading>
        </el-col>
        <el-col :span="12" style="text-align:right;">
          <el-button type="primary" size="small" @click="dialogVisible= true">新增客户</el-button>
        </el-col>
      </el-row>
      <el-form  ref="form" v-bind="getFormProps()">
        <el-row>
          <el-col :span="18">
            <el-date-picker
              size="small"
              placeholder="请选择时间段"
              v-model="timerg"
              type="daterange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
            </el-date-picker>
            <el-input size="small" placeholder="请输入搜索内容" v-model.trim="query.searchValue"  class="search-input"/>
            <el-button size="small" native-type="submit" type="primary-plain" >搜索</el-button>
          </el-col>
        </el-row>
      </el-form>

      <DataStatics :data="data">
      </DataStatics>

      <el-row style="margin: 20px 0;">
        <el-col :span="4" :offset="20">
          <el-button class="fr" size="small"  @click="exportExcel">导出</el-button>
        </el-col>
      </el-row>
      <el-table :data="list.list" style="width: 100%">
        <el-table-column
          prop="rankNO"
          label="排名"
          sortable
          width="80">
        </el-table-column>
        <el-table-column
          prop="saleName"
          label="销售人员">
          <template slot-scope="scope">
            <p :title="scope.row.saleName" class="hidden">{{scope.row.saleName}}</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="newAddCount"
          label="新增"
          sortable>
        </el-table-column>
        <el-table-column
          prop="dealCount"
          label="成交"
          sortable>
        </el-table-column>
        <el-table-column
          prop="followCount"
          label="跟进"
          sortable>
        </el-table-column>
        <el-table-column
          prop="trialCount"
          label="试课"
          sortable>
        </el-table-column>
        <el-table-column
          prop="totalCount"
          label="客户总数"
          sortable>
        </el-table-column>
        <el-table-column
          prop="lastFollowTime"
          label="跟进时间"
          sortable>
          <template slot-scope="scope">
            <span>{{ Number.isInteger(scope.row.lastFollowTime) ? new Date(scope.row.lastFollowTime).format() : ''}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="详情">
          <template slot-scope="scope">
              <el-button  type="link" @click="toDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-bind="getPaginationProps(list)"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange">
      </el-pagination>
    </div>

    <el-dialog 
      v-if="dialogVisible"
      title="新增客户"
      :visible.sync="dialogVisible"
      @close="resetForm">
      <el-form ref="form1" :model="form" :rules="rules" novalidate="novalidate" label-width="110px" >
        <el-scrollbar  wrap-class="sale-form-wrapper">
        <el-form-item
          prop="phone"
          label="监护人手机："
          :rules="
          [{required: true, message: '请输入监护人手机'},
          validator.rule.isPhone]"
        >
          <el-input class="sale-input" :maxlength="11" v-model.trim="form.phone"></el-input>
        </el-form-item>
        <el-form-item
          prop="trueName"
          label="姓名："
          :rules="
          [{required: true, message: '请输入学员姓名'},
          validator.rule.username]"
        >
          <el-input class="sale-input" v-model.trim="form.trueName" :maxlength="40"></el-input>
        </el-form-item>
        <el-form-item
          prop="sex"
          label="性别："
        >
          <el-radio-group v-model="form.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          prop="idNo"
          label="证件号码："
          :rules=" [
            this.form.idType == 1 ? Object.assign({},{message: '身份证格式不正确',trigger: 'blur'},  validator.rule.idCard) : {}
          ]"
        >
          <e-identity
            v-model.trim="form.idNo"
            :select-value.sync="form.idType"
            input-style="width:247px" 
             />
        </el-form-item>
        <el-form-item
          prop="address"
          label="家庭住址："
        >
          <el-input class="sale-input" v-model.trim="form.address" :maxlength="200"></el-input>
        </el-form-item>
        <el-form-item
          prop="origin"
          label="籍贯："
        >
          <e-address-cascader class="sale-input" v-model.trim="form.origin" :grade="2" 
            :label.sync="form.location"></e-address-cascader>
        </el-form-item>
        <el-form-item
          prop="height"
          label="身高："
        >
          <el-input-number :bit="0.01" :max="300" class="sale-input" v-model.trim="form.height" >
            <template slot="append">cm</template>
          </el-input-number>
        </el-form-item>
        <el-form-item
          prop="height"
          label="体重："
        >
          <el-input-number :bit="0.01" :max="200"  class="sale-input" v-model.trim="form.weight" >
            <template slot="append">kg</template>
          </el-input-number>
        </el-form-item>
        
        
        <el-form-item
          prop="saleman"
          label="销售人员："
          :rules="[{required: true, message: '请选择销售人员'}]"
        >
          <el-select class="sale-input" v-model.trim="form.saleman">
            <el-option v-for="item in salemanList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="schoolId"
          label="咨询校区："
          :rules="[{required: true, message: '请选择咨询校区'}]"
        >
          <el-select class="sale-input" v-model.trim="form.schoolId">
            <el-option v-for="item in train_school_list"
              :key="item.label"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="source"
          label="客户来源："
          :rules="[{required: true, message: '请选择客户来源'}]"
        >
          <el-select class="sale-input"  v-model.trim="form.source">
            <el-option v-for="item in sourceOptions"
              :key="item.label"
              :label="item.label"
              :value="item.value">                      
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="email"
          label="电子邮箱："
          :rules="[validator.rule.email]"
        >
          <el-input class="sale-input" v-model.trim="form.email"></el-input>
        </el-form-item>
        </el-scrollbar>
        <div style="text-align: center;margin-top:20px;">
          <el-button @click="submit()" type="primary">
            保存
          </el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  import EAddressCascader from '@e-ui/AddressCascader'
  import EIdentity from '@e-ui/Identity'
  import DataStatics from '../../components/DataStatics'
  import validator from 'utils/validator'
  import { pagingList } from 'utils/mixins'
  import {downloadFile, cloneObj} from 'utils' // eslint-disable-line
  import api from 'api/train'
  import {mapGetters} from 'vuex'
  export default {
    mixins: [pagingList],
    components: {
      EIdentity,
      EAddressCascader,
      DataStatics
    },
    computed: {
      ...mapGetters({
        train_school_list: 'train_school_list'
      })
    },
    created () {
      if (!this.train_school_list.length) {
        this.getSchoolList()
      }
      this.getSaleManList()
    },
    mounted () {
    },
    watch: {
      timerg () {
        this.query.startDate = (Array.isArray(this.timerg) && +new Date(this.timerg[0]) > 0) ? +new Date(this.timerg[0]) : ''
        this.query.endDate = (Array.isArray(this.timerg) && +new Date(this.timerg[1]) > 0) ? +new Date(this.timerg[1]) : ''
      }
    },
    data () {
      let sOptions = ['地推', '传单', '转介绍', '地摊', '公开课', '电销', '微信'] // 客户来源
      let sourceOptions = sOptions.map((item, index) => {
        return {
          label: item,
          value: index + 1
        }
      })
      return {
        validator,
        rules: {},
        dialogVisible: false,
        data: [
          {
            label: '新增',
            key: 'newAddCount',
            value: 0
          },
          {
            label: '成交',
            key: 'dealCount',
            value: 0
          },
          {
            label: '总数',
            key: 'totalCount',
            value: 0
          },
          {
            label: '跟进',
            key: 'followCount',
            value: 0
          },
          {
            label: '试课',
            key: 'trialCount',
            value: 0
          }
        ],
        list: [],
        query: this.getQuery({
          searchValue: '',
          startDate: '',
          endDate: ''
        }),
        timerg: '',
        selecteRange: '1',
        pickerOptions: {
          shortcuts: [
            {
              text: '最近一天',
              onClick (picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24)
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近一周',
              onClick (picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
                picker.$emit('pick', [start, end])
              }
            },
            {
              text: '最近一个月',
              onClick (picker) {
                const end = new Date()
                const start = new Date()
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
                picker.$emit('pick', [start, end])
              }
            }
          ]
        },
        form: {
          phone: '',
          schoolId: '',
          height: '',
          weight: '',
          saleman: '',
          trueName: '',
          school: '',
          sex: 1,
          origin: [],
          source: '',
          address: '',
          idType: 1,
          idNo: '',
          email: '',
          location: []
        },
        schoolList: [],
        sourceOptions: sourceOptions,
        salemanList: []
      }
    },
    methods: {
      submit () {
        this.$refs.form1.validate((valid) => {
          if (valid) {
            let obj = cloneObj(this.form)
            let data = {
              saleUserId: obj.saleman,
              parentMobile: obj.phone,
              name: obj.trueName,
              sex: obj.sex,
              idType: obj.idType,
              idNo: obj.idNo,
              origine: obj.source,
              address: obj.address,
              height: Number(obj.height),
              weight: Number(obj.weight),
              schoolId: obj.schoolId,
              email: obj.email,
              isCover: 2
            }
            let loca = {
              province: obj.origin[0] || '',
              city: obj.origin[1] || ''
            }
            let postData = {}
            if (this.form.origin && this.form.origin.length) {
              postData = Object.assign({}, data, loca)
            } else {
              postData = Object.assign({}, data)
            }
            api.addStudentFromSale(postData).then((res) => {
              this.dialogVisible = false
              this.resetForm()
              this.fetch()
            })
          } else {
            let node = this.$el.querySelector('.is-error')
            if (node) {
              node.scrollIntoView && node.scrollIntoView(true)
            }
            return false
          }
        })
      },
      // 清除form所有字段
      resetForm () {
        this.$refs.form1.resetFields()
      },
      getSchoolList () {
        api.schoolList({
          page: 1,
          rows: 1000,
          isSale: true
        }).then((res) => {
          if (res.data.list) {
            this.schoolList = res.data.list.map(item => {
              return {
                label: item.schoolName,
                value: item.id
              }
            })
            this.$store.commit('TRAN_SCHOOL_LIST', this.schoolList)
          }
        })
      },
      fetch (query) {
        api.saleList(this.query).then((res) => {
          this.list = res.data
        })
        this.getDataStatics()
      },
      // 数据统计
      getDataStatics () {
        api.saleDataStatistics({
          startDate: this.query.startDate > 0 ? this.query.startDate : '',
          endDate: this.query.endDate > 0 ? this.query.endDate : ''
        }).then((res) => {
          this.data.forEach(item => {
            for (let k in res.data) {
              if (item.key === k) {
                item.value = res.data[k]
              }
            }
          })
        })
      },
      getSaleManList () {
        api.getSaleManList({}).then((res) => {
          if (res.data) {
            this.salemanList = res.data.map(item => {
              return {
                label: item.nickName,
                value: item.userId
              }
            })
          }
        })
      },
      toDetail (item) {
        this.$store.commit('TRAN_SALE_NAME', item.saleName)
        this.$router.push({
          path: '/training/sale/detail',
          query: {
            userId: item.saleUserId
          }
        })
      },
      exportExcel () {
        let startDate = this.$route.query.startDate || ''
        let endDate = this.$route.query.endDate || ''
        let searchValue = this.$route.query.searchValue || ''
        let url = `/api/train/sale/export/SaleRank?startDate=${startDate}&endDate=${endDate}&searchValue=${searchValue}`
        var _this = this
        downloadFile(url, '销售列表.xls', function (blob) {
          _this.$message({
            message: '下载出错，请稍后再试',
            type: 'warning'
          })
        })
      }
    }
  }
</script>
<style lang="scss" scoped>

.search-input{
  width: 237px;
}
.number-input{
  width: 340px;
}
</style>
<style lang="scss">
.sale-form-wrapper{
  max-height: 525px;
  padding-bottom: 20px;
  overflow-y: scroll;
  overflow-x: hidden;
  .sale-input{
    width:362px;
  }
}
.identity {
  .el-form-item__content{
    margin-left:15px!important;
  }  
}
</style>
